package cn.butcher21.controller.timeline;

import cn.butcher21.pojo.TimeLineEntity;
import cn.butcher21.utils.DButil;
import com.google.gson.Gson;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * butcher create in 2021/03/07/12:43,
 * <p>
 * 返回数据库中存在的时间线数据
 */
@WebServlet("/timeLine")
public class TimeLine extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DButil dButil = new DButil();

        PreparedStatement ps = dButil.getPs("select time,content,pic from yt_timeline");
        try {
            ResultSet rs = dButil.getRs(ps.executeQuery());
            List<TimeLineEntity> list = new ArrayList<>();

            while (rs.next()) {
                TimeLineEntity timeLineEntity = new TimeLineEntity();
                timeLineEntity = new TimeLineEntity();
                timeLineEntity.setSrc(rs.getString("pic"));
                timeLineEntity.setTime(rs.getString("time"));
                timeLineEntity.setContent(rs.getString("content"));
                list.add(timeLineEntity);
            }
            Gson gson = new Gson();
            String json = gson.toJson(list);

            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print(json);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            dButil.closeAll();
        }
    }
}
